package com.user.query.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import com.user.query.utils.ConstantUtils;

public class LoginFilter  extends OncePerRequestFilter{

	@Override
	protected void doFilterInternal(HttpServletRequest req,	HttpServletResponse resp, FilterChain chain) throws ServletException, IOException {
		// 不执行过滤的请求，直接通过
			chain.doFilter(req, resp);

	}

	/***
	 * 备份方法
	 * @param req
	 * @param resp
	 * @param chain
	 * @throws ServletException
     * @throws IOException
     */
	//@Override
	protected void doFilterInternal2(HttpServletRequest req,	HttpServletResponse resp, FilterChain chain) throws ServletException, IOException {
		FilterConfig filterConfig = this.getFilterConfig();
		String redirectURL = filterConfig.getInitParameter("redirectURL");
		String[] notCheckURLList = filterConfig.getInitParameter("notCheckURLList").split(";");
		String uri = req.getRequestURI();
		String projectName = req.getContextPath();
		uri = (uri.startsWith(projectName))?uri:projectName+uri;	// 请求路径加上项目名称

		// 是否过滤
        boolean doFilter = false;
		for(String noCheckURL:notCheckURLList) {
			if (uri.endsWith("/") || uri.indexOf(noCheckURL) != -1) {
                // 如果uri中包含不过滤的uri，则不进行过滤
                doFilter = true;
                break;
            }
		}

		if(!doFilter) {
			HttpSession session = req.getSession();
			if(session.getAttribute(ConstantUtils.USERINFO) == null) {
				if(isAjaxRequest(req)) { // ajax请求，返回session超时提示
					resp.setCharacterEncoding("UTF-8");
					resp.sendError(HttpStatus.UNAUTHORIZED.value(), "您已经太长时间没有操作,请刷新页面");
                    return;
				}
				resp.sendRedirect(projectName+redirectURL);
				return;
			}else {	// session中有登录信息，直接通过
				chain.doFilter(req, resp);
			}
		}else {	// 不执行过滤的请求，直接通过
			chain.doFilter(req, resp);
		}
	}
	
	
	/** 判断是否为Ajax请求  
     * @param request 
     * @return 是true, 否false  
     */  
    public static boolean isAjaxRequest(HttpServletRequest request) {  
        String header = request.getHeader("X-Requested-With");   
        if(header != null && "XMLHttpRequest".equals(header)) {
        	
            return true;   
        }else {
            return false;    
        }
    } 


}
